package com.etymgiko.lyricshere.web;

import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etymgiko.lyricshere.model.Artist;
import com.etymgiko.lyricshere.model.Song;
import com.etymgiko.lyricshere.manager.ArtistManager;
import com.etymgiko.lyricshere.manager.SongManager;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 *
 * @author Ivan Holub
 */
public class SongListController extends AbstractController {

    private ArtistManager artistManager;

    private SongManager songManager;


    public void setArtistManager(ArtistManager artistManager) {
        this.artistManager = artistManager;
    }

    public void setSongManager(SongManager songManager) {
        this.songManager = songManager;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mav = new ModelAndView("songList");
        List<Song> songs = songManager.getSongs();
        List<Artist> artists = artistManager.getArtists();
        List<SongListItem> list = new ArrayList<SongListItem>();
        for (Song song : songs) {
            Artist artist = findArtist(artists, song.getArtistId());
            SongListItem item = new SongListItem();
            item.setArtistCode(artist.getCode());
            item.setArtistName(artist.getName());
            item.setSongCode(song.getCode());
            item.setSongTitle(song.getTitle());
            list.add(item);
        }
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                SongListItem item1 = (SongListItem) o1;
                SongListItem item2 = (SongListItem) o2;
                int a = item1.getArtistName().compareTo(item2.getArtistName());
                if (a != 0) {
                    return a;
                }
                return item1.getSongTitle().compareTo(item2.getSongTitle());
            }
        });
        mav.addObject("list", list);
        return mav;
    }

    private Artist findArtist(List<Artist> artists, Long id) {
        Artist retValue = null;
        for (Artist a : artists) {
            if (id.equals(a.getId())) {
                retValue = a;
                break;
            }
        }
        return retValue;
    }
}